<script>
	import Vue from 'vue'
	import config from './config'
	import store from '@/store'
	import {
		getToken
	} from '@/utils/auth'
	import mqttClient from '@/utils/mqttClient'

	export default {
		onLaunch: function() {
			// 1. 初始化系统信息（保持不变）
			this.initSystemInfo()
			// 2. 初始化应用
			this.initApp()
			// 3. 初始化MQTT连接（新增）
			this.initMQTT()
		},

		onHide: function() {
			// 应用进入后台时断开MQTT（可选）
			// mqttClient.disconnect()
		},

		onShow: function() {
			// 应用回到前台时恢复连接
			if (!mqttClient.connected) {
				mqttClient.init()
			}
		},

		methods: {
			/* 原有方法保持不变 */
			initSystemInfo() {
				uni.getSystemInfo({
					success: function(e) {
						// #ifndef MP
						Vue.prototype.StatusBar = e.statusBarHeight;
						if (e.platform == 'android') {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 45;
						};
						// #endif
						// #ifdef MP-WEIXIN
						Vue.prototype.StatusBar = e.statusBarHeight;
						let custom = wx.getMenuButtonBoundingClientRect();
						Vue.prototype.Custom = custom;
						Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
						// #endif    
						// #ifdef MP-ALIPAY
						Vue.prototype.StatusBar = e.statusBarHeight;
						Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
						// #endif
					}
				})
			},

			initApp() {
				this.initConfig()
				//#ifdef H5
				this.checkLogin()
				//#endif
				

			},

			initConfig() {
				this.globalData.config = config
			},

			checkLogin() {
				if (!getToken()) {
					this.$tab.reLaunch('/pages/login')
				}
			},

			/* 新增MQTT相关方法 */
			initMQTT() {
				// 挂载到Vue原型
				Vue.prototype.$mqtt = mqttClient

				// 全局错误监听
				mqttClient.on('error', (err) => {
					console.error('[全局MQTT错误]', err)
					uni.showToast({
						title: 'MQTT连接异常',
						icon: 'none'
					})
				})

				// // 连接状态变化监听
				// mqttClient.on('connected', () => {
				// 	console.log('[MQTT] 全局连接成功')
				// 	this._handleGlobalSubscriptions()
				// })
				
				// 初始化连接
				if (config.mqtt.autoConnect !== false) {
					mqttClient.init()
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "plugins/colorui/main.css";
	@import "plugins/colorui/icon.css";
	@import "plugins/uview-ui/index.scss";
	@import '@/static/scss/index.scss';
</style>